package com.mhkj.base.itemInfo.item.controller;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mhkj.base.itemInfo.item.entity.Item;
import com.mhkj.base.itemInfo.item.entity.TreeOrgItemVo;
import com.mhkj.base.itemInfo.item.service.ItemService;
import com.mhkj.base.rbac.role.entity.SystemRole;
import com.mhkj.base.region.entity.TSysNation;
import com.mhkj.base.region.service.NationService;
import com.mhkj.common.util.ItemHelper;
import com.mics.core.common.componet.Pagination;
import com.mics.core.common.componet.ResponseMessage;
import com.mics.core.common.exception.ErrorCode;
import com.mics.core.common.exception.OperateException;
import com.mics.core.common.util.UserHelper;
import com.mics.core.common.util.json.JsonUtils;
import com.mics.core.system.base.controller.BaseController;
import com.mics.core.system.organizational.bean.Company;
import com.mics.core.system.organizational.bean.CompanyData;
import com.mics.core.system.organizational.bean.Employee;
import com.mics.core.system.organizational.service.OrgService;
import com.mics.core.system.rbac.service.DictionaryService;

/**
 * 项目
 */

@Controller
@RequestMapping("/item")
public class ItemController extends BaseController<Item> {
	@Autowired
	private ItemService itemService;
	@Autowired
	private NationService nationService;
	@Autowired
	private OrgService orgService;
	@Autowired
	private DictionaryService dictionaryService;
	@Resource
	private ItemHelper itemHelper;

	/**
	 * 分页查询项目
	 * 
	 */
	@RequestMapping(value="/listByPage", method=RequestMethod.POST)
	@ResponseBody
	public Pagination<Item> listByPage( Item item, int pageIndex, int pageSize ) {
		Pagination<Item> pagination = itemService.listByPage(item,pageIndex, pageSize);
		List<Item> list = pagination.getData();
		for (Item item2 : list) {
//			int status = item2.getStatus();
//			if(!StringUtils.isEmpty(status)) {
//				Dictionary dict = dictionaryService.getById(status);
//				if(!StringUtils.isEmpty(dict)) {
//					String value = dict.getValue();
//					item2.setStatusName(value);
//				}
//			}
			Company company = orgService.getCompanyById(item2.getAffiliatedCompanyId());
			if(!StringUtils.isEmpty(item.getFunctionaryId())) {
			Employee employeeInfo = orgService.employeeInfo(item.getFunctionaryId());
			if(employeeInfo!=null) {
				item.setFunctionaryName(employeeInfo.getName());
			}
			
			}
			if(company!=null) {
				item2.setAffiliatedCompanyName(company.getCompanyname());
		}}
		
		return pagination;
	}

	/**
	 * 保存
	 * 
	 */
	@RequestMapping(value="/save", method=RequestMethod.POST)
	@ResponseBody
	public ResponseMessage save(Item item) {
		
		Long cityId = item.getCityId();
		if(StringUtils.isEmpty(cityId)) {
			return ResponseMessage.createMessage(false, ErrorCode.PARAM_ERROR, "城市为空!");
		}
		TSysNation nation = nationService.getById(cityId);
		item.settSysNation(nation);
		String message = itemService.save(item);
		return ResponseMessage.createMessage("ok".equals(message), message);
	}

	/**
	 * 修改
	 * 
	 */
	@RequestMapping(value="/edit", method=RequestMethod.POST)
	@ResponseBody
	public ResponseMessage edit(Item item) {
		Long cityId = item.getCityId();
		TSysNation nation = nationService.getById(cityId);
		item.settSysNation(nation);
		String message = itemService.edit(item);
		return ResponseMessage.createMessage("ok".equals(message), message);
	}

	/**
	 * 删除
	 * 
	 */
	@RequestMapping(value="/del",method={RequestMethod.POST})
	@ResponseBody
	public ResponseMessage del(Long id) {
		try{
			Item item = new Item();
			item.setId(id);
			String message = itemService.del(item);
			return ResponseMessage.createMessage("ok".equals(message), message);
		}catch(Exception e){
			throw new OperateException(ErrorCode.DELETE, "项目已经被引用不能删除");
		}
		
	}

	/**
	 * 查询所有项目
	 * 
	 */
	@RequestMapping(value="/list", method=RequestMethod.POST)
	@ResponseBody
	public List<Item> listAll() {
		List<Item> list = itemService.findAll();
		List<Item> myItems = new ArrayList<Item>();
		for (Item item : list) {
			List<Item> itemeds = itemHelper.getCurrentUserItems();
			for(Item itemed :itemeds){
				if(itemed.getId().equals(item.getId())){
					Company company = orgService.getCompanyById(item.getAffiliatedCompanyId());
					if(!StringUtils.isEmpty(item.getFunctionaryId())) {
						Employee employeeInfo = orgService.employeeInfo(item.getFunctionaryId());
						if(employeeInfo!=null) {
							item.setFunctionaryName(employeeInfo.getName());
						}
						}
					if(company!=null) {
						item.setAffiliatedCompanyName(company.getCompanyname());
					}
					myItems.add(itemed);
				}
			}
			
		}
		return myItems;
	}
	
	/**
	 * 查询项目信息
	 */
	@RequestMapping(value="/info", method=RequestMethod.POST)
	@ResponseBody
	public Item info(@RequestParam(value = "id", required = true) long id) {
		Item item = itemService.getById(id);
		Company company = orgService.getCompanyById(item.getAffiliatedCompanyId());
		if (!StringUtils.isEmpty(item.getFunctionaryId())) {
			Employee employeeInfo = orgService.employeeInfo(item.getFunctionaryId());
			if (employeeInfo != null) {
				item.setFunctionaryName(employeeInfo.getName());
			}
		}
		if (company != null) {
			item.setAffiliatedCompanyName(company.getCompanyname());
		}
		return item;
	}



	/**
	 * 获取已经建立项目的省
	 */
	@RequestMapping(value="/getProvinceWithItem", method=RequestMethod.POST)
	@ResponseBody
	public HashSet<TSysNation> getProvinceWithItem(){
		List<Item> list =itemService.getProvinceWithItem();
		HashSet<TSysNation> listTn = new HashSet<TSysNation>();
		for (Item item : list) {
			TSysNation gettSysNation = item.gettSysNation();
			
			Long parentId = gettSysNation.getParentId();
			
			if(!StringUtils.isEmpty(parentId)) {
				TSysNation byId = nationService.getById(parentId);
				listTn.add(byId);
			}
			
		}
		return listTn;
	}
	
	
	/**
	 * 获取已经建立项目对应的省下城市
	 */
	@RequestMapping(value="/getCityWithProvince", method=RequestMethod.POST)
	@ResponseBody
	public HashSet<TSysNation> getCityWithProvince(Long provinceId){
		List<Item> list =itemService.getCityWithProvince(provinceId);
		HashSet<TSysNation> listTn = new HashSet<TSysNation>();
		for (Item item : list) {
			TSysNation gettSysNation = item.gettSysNation();
			listTn.add(gettSysNation);
		}
		return listTn;
	}
	


	/**
	 * 批量删除项目
	 */
	@RequestMapping(value="/delAll", method=RequestMethod.POST)
	@ResponseBody
	public ResponseMessage delAll(@RequestParam(value="id",required=true) String id) {
		String[] split = id.split(",");
		for (String str : split) {
			long parseLong = Long.parseLong(str);
			Item item = itemService.getById(parseLong);
			itemService.del(item);
		}
		
		return ResponseMessage.createMessage(true, "ok");
	}
	/**
	 * 获取所有公司下面的项目树
	 */
	@RequestMapping(value="/findTreeOrgItem", method=RequestMethod.POST)
	@ResponseBody
	public List<TreeOrgItemVo> findTreeOrgItem() {
		 
		CompanyData companiedData =  orgService.listCompanys();
		if(companiedData!=null) {
		List<Company> childCompanyList = companiedData.getChildCompanyList();
		List<TreeOrgItemVo> list = new ArrayList<TreeOrgItemVo>();
		TreeOrgItemVo e = new TreeOrgItemVo();
		e.setId(companiedData.getHeadCompany().getId());
		e.setName(companiedData.getHeadCompany().getCompanyname());
		list.add(e);
		for (Company company : childCompanyList) {
			TreeOrgItemVo en = new TreeOrgItemVo();
			String id = company.getId();
			en.setId(id);
			en.setPid(company.getParentid());
			en.setName(company.getCompanyname());
			List<Item>	listItem = itemService.getListItemByaffiliatedCompanyId(id,null,null);
			for (Item item : listItem) {
				TreeOrgItemVo enit = new TreeOrgItemVo();
				String itemId = item.getId().toString();
				enit.setId(itemId);
				enit.setPid(id);
				enit.setName(item.getName());
				enit.setItem(true);
				list.add(enit);
			}
			list.add(en);
		}
		
		return list;
		}else {
			return null;
		}
	}
 
	
	/**
	 * 获取省份下的所有项目
	 */
	@RequestMapping(value="/getItemWithCityId", method=RequestMethod.POST)
	@ResponseBody
	public List<Item> getItemWithCityId(Long  provinceId,Long cityId){
		
		List<Item> list =itemService.getItemWithCityId(provinceId,cityId);
		return list;
	}
	
	
	/**
	 * 同一个公司下不能有相同名称的项目
	 */
	
	@RequestMapping(value="/checkItemName", method=RequestMethod.POST)
	@ResponseBody
	public Boolean checkItemName(Long id,String  affiliatedCompanyId,String name){
		
		
		List<Item> list =itemService.checkItemName(affiliatedCompanyId,name);
		
		if(StringUtils.isEmpty(name)) {
			return false;
		}
		
		if(StringUtils.isEmpty(id)) {
			if(list.isEmpty()) {
				return true;//可以添加
			}else {
				return false;
			}
			
		}else {
			if(list.size()<=1) {
				return true;//可以修改
			}else {
				return false;
			}
			
			
		}
		
	}
	
	@RequestMapping("/grantRole")
	@ResponseBody
	public ResponseMessage grantRole(Item item,String roleIds){
		if(roleIds != null){
			itemService.grantRole(item,roleIds);
		}
		return ResponseMessage.createMessage(true, "分配角色成功");
	}
	
	
	@RequestMapping("/listRoles")
	@ResponseBody
	public void listRoles(HttpServletResponse response,long id){
		Item item = itemService.getById(id);
		List<SystemRole> systemRoles = item.getSystemRoles();
		JsonUtils.sendJsonFromList(response, true,"获取数据成功", systemRoles, new String[]{"id","roleName","name","code"},
				"id","roleName","name","code");
		}
	/**
	 * 获取当前登录用户
	 * 
	 */
	@RequestMapping(value="/getUserInfo", method=RequestMethod.POST)
	@ResponseBody
	public Employee getUserInfo() {
		 Employee currentEmployee = UserHelper.getCurrentEmployee();
		return currentEmployee;
	}
}
